﻿using Inovout.Repositories;
using NHibernate;
using NHibernate.Criterion;
using System.Data;


namespace Inovout.NumberGenerator
{
    public class SequenceNumberRepository : DataObjectRepository<SequenceNumber>
    {
        public int Next(string key, int period, int seed, int increment)
        {
            ISession session = OpenSession();
            SequenceNumber sequenceNumber;
            using (ITransaction transaction = session.BeginTransaction(IsolationLevel.Serializable))
            {
                sequenceNumber = base.Find(Restrictions.Eq("Key", key), Restrictions.Eq("Period", period));
                if (sequenceNumber == null)
                {
                    sequenceNumber = new SequenceNumber();
                    sequenceNumber.Key = key;
                    sequenceNumber.Period = period;
                    sequenceNumber.Increment = increment;
                }
                else
                {
                    sequenceNumber.Increment += seed;
                }
                base.Save(sequenceNumber);
            }
            return sequenceNumber.Increment;

        }
    }
}
